#include "stdio.h"
#include "stdint.h"
#include "string.h"
#include "parameters.h"
#include "DevicesTime.h"
#include "FeedFrame.h"
#include "FeedPack.h"
#include "FeedApp.h"


uint32_t g_uiHeadbeat = 0;


/* 主动发送心跳 */
int8_t cFeedAppHeartbeat(void)
{
    static int64_t lTimeStop = 0;
    int64_t lTime;

    if(((lTime = lTimebaseGet()) - lTimeStop) > 1000000 * 15)
    {
        lTimeStop = lTime;

        cFeedPackFrameUpdateInt(FEED_ADDR_DEVICE,   FEED_ADDR_IOT, 0, g_uiHeadbeat);
        cFeedPackJsonUpdateInt(FEED_ADDR_SERVER,    FEED_ADDR_IOT, 0, g_uiHeadbeat);
        ++g_uiHeadbeat;

    }

    return 0;
}

/* 定时获取服务器时间 */
int8_t cFeedAppTimeGet(void)
{
    static int64_t lTimeStop = 0;
    int64_t lTime;

    if(((lTime = lTimebaseGet()) - lTimeStop) > 1000000 * 15)
    {
        /* 当时间戳小于2025年时，及时获取时间 */
        if(((lTime - lTimeStop) > 1000000 * 60 * 15) || (lTimestampGet() < 1735660800000000LL))
        {
            lTimeStop = lTime;

            cFeedPackJsonSingleGet(FEED_ADDR_SERVER, FEED_ADDR_IOT, 3);
        }
    }

    return 0;
}

/* 获取MCU MTU */
int8_t cFeedAppMcuMtuGet(void)
{
    static int64_t lTimeStop = 0;
    int64_t lTime;
    ParametersType *ptypeParameters = ptypeParametersInfoGet();

    if((ptypeParameters->frameMcuMtu == 0) && (((lTime = lTimebaseGet()) - lTimeStop) > 1000000 * 15))
    {
        lTimeStop = lTime;

        cFeedPackFrameSingleGet(FEED_ADDR_DEVICE, FEED_ADDR_IOT, 2);
    }

    return 0;
}

int8_t cFeedKernel(void)
{
    cFeedAppHeartbeat();

    cFeedAppTimeGet();

    cFeedAppMcuMtuGet();

    return 0;
}